package com.robotserver.orders.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author jianghan
 * @date 2019-10-15 13:55
 */
//@Component
public class ZkApi {
    /*private static Logger logger = LoggerFactory.getLogger(ZkApi.class);

    @Autowired
    private CuratorFramework zkClient;
    @Autowired
    private ZkConfig zkConfig;

    *//**
     * 创建临时节点
     * @param path
     * @param data
     *//*
    public void createEphemeralNode(String path, String data){
        try {
            deleteNode(path);
            String node = zkConfig.getOrderServerNode()+path;
            logger.info("create node:{},data:{}",new Object[]{node,data});
            zkClient.create().creatingParentsIfNeeded().
                    withMode(CreateMode.EPHEMERAL).
                    withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).
                    forPath(node,data.getBytes("UTF-8"));
        } catch (Exception e) {
            logger.error("create node err:",e);
        }
    }

    *//**
     * 获取子节点列表
     * @param path
     * @return
     *//*
    public List<String> getChildren(String path){
        try {
            if (StringUtils.isBlank(path)){
                path = zkConfig.getOrderServerNode();
                if (path.endsWith("/")){
                    path = path.substring(0,path.length()-1);
                }
            }
            return zkClient.getChildren().forPath(path);
        } catch (Exception e) {
            logger.error("get node list err:",e);
        }
        return null;
    }

    *//**
     * 检查节点是否存在
     * @param path
     *//*
    public String getNodeData(String path){
        try {
            String node = zkConfig.getOrderServerNode()+path;
            byte[] data = zkClient.getData().forPath(node);
            if (data==null || data.length==0){
                return null;
            }
            String dataStr = new String(data,"UTF-8");
            logger.info("get node data:{}",dataStr);
            return dataStr;
        } catch (Exception e) {
            logger.error("get node data err:",e);
        }
        return null;
    }

    *//**
     * 删除节点
     * @param path
     *//*
    public void deleteNode(String path){
        try {
            String node = zkConfig.getOrderServerNode()+path;
            logger.info("delete node:{}",node);
            zkClient.delete().guaranteed().
                    deletingChildrenIfNeeded().forPath(node);
        } catch (Exception e) {
            logger.error("delete node err:",e);
        }
    }*/

}
